// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})
const axios = require('axios');
const cheerio = require('cheerio');
const db = cloud.database();
async function getReq(url, data) {
  return new Promise(function (resolve, reject) {
    axios({
      method: 'GET',
      url: url,
      data: data,
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1 Edg/92.0.4515.131'
      }
    }).then(response => {
      // console.log(response)
      resolve(response.data)
    })
  })
}

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  let bookNo = event.bookNo
  let bookUrl = 'http://interlib.sdust.edu.cn/opac/m/book/' + bookNo
  let reqData = await getReq(bookUrl, {});
  $ = cheerio.load(reqData)
  /**爬虫爬取馆藏 */
  let storeList = []
  let storeData = {};
  let res = $('li p').each(function (index, ele) {
    /**组装馆藏信息 */
    let baseStr = $(this).text().trim();
    console.log(baseStr)
    if (index % 5 == 0) {
      //条码
      storeData.codeNo = baseStr
    } else if (index % 5 == 1) {
      storeData.lib = baseStr
    } else if (index % 5 == 2) {
      storeData.libLoaction = baseStr
    } else if (index % 5 == 3) {
      storeData.storeStatus = baseStr
    } else if (index % 5 == 4) {
      storeData.searchCode = baseStr
      storeList.push(storeData)
      storeData = {};
    }
    
  })
  return storeList;
}